# -*- coding: utf-8 -*-
# @Time    : 2024/12/18 21:25
# @Author  : xiangbo
# @Email   : xiangbo@163.com
# @File    : mail.py
# @Software: PyCharm
# 邮件模块
import smtplib
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from config.config import Config
from common.consts import REPORT_PATH
from common.log import Log

c = Config()
logger = Log.get_logger()


def send_mail(report):
    # 创建邮件对象
    msg = MIMEMultipart()
    # 配置email的头
    msg["Subject"] = c.get_email("subject")
    msg["From"] = c.get_email("user")
    msg["To"] = c.get_email("receiver")

    # 格式化email的正文，同时将报告以附件形式发送
    with open(os.path.join(REPORT_PATH, report), 'rb') as f:
        body = f.read()
        attach = MIMEBase('zip', 'zip', filename=report)
        # 给附件重命名，一般和源码文件一样
        attach.add_header('Content-Disposition', 'attachment', filename=('gb2312', '', report))
        attach.set_payload(body)
        encoders.encode_base64(attach)
        msg.attach(attach)

    try:
        # 连接smtp服务器，发送邮件
        smtp = smtplib.SMTP()
        smtp.connect(c.get_email("server"))
        smtp.login(c.get_email("user"), c.get_email("pwd"))
        smtp.sendmail(c.get_email("user"), c.get_email("receiver"), msg.as_string())

    except Exception as e:
        print(e)
        print("发送失败")
        logger.error("邮件发送失败，请检查邮件配置")
    else:
        print("发送成功")
        logger.info("邮件发送成功")
    finally:
        smtp.quit()
